//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.MachineOperate;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.MachineDao;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.util.*;
import io.swagger.models.auth.In;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class MachineService {
    private static final Logger logger = LoggerFactory.getLogger(MachineService.class);
    private HttpServletRequest result;
    @Resource
    private MachineDao machineDao;
    @Autowired(required = false)
    @Lazy
    private WxService wxService;
    @Autowired(required = false)
    @Lazy
    private MqttService mqttService;
    @Resource
    @Lazy
    private OrderService orderService;
    @Resource
    private  RedisService redisService;

    @Autowired(required = false)
    private  StatisticService statisticService;
    @Resource
    @Lazy
    private CouponService couponService;
    @Resource
    private  SysDicService sysDicService;
    @Autowired(required = false)
    @Lazy
    private  PriceTimeService priceTimeService;
    @Resource
    @Lazy
    private StoreService storeService;
    @Resource
    private LappService lappService;


    public MachineService() {
    }

    @Transactional(rollbackFor = Exception.class)
    public int addMachine(Machine machine) {
        machine.setStatus(2);
        machine.setWorkState(102);
        if (StringUtils.isBlank(machine.getServiceTime())) {
            machine.setServiceTime("08:00-22:00");
        }

        if (machine.getProfitRatio() == null) {
            machine.setProfitRatio(Global.DEFAULT_PROFIT_RATE);
        }
        if(machine.getIsDirect()==null)
        {
            machine.setStatus(2);
        }
        int changeRow = this.machineDao.addMachine(machine);
        if (changeRow > 0) {
            this.generateWxCode(machine);
        }
        //添加好机器后，去后台价格时段默认配置一个平台价格
        PriceTime priceTime=this.priceTimeService.findPriceTimeByPriceId(0);
        PriceTime newMachinePriceTime=new PriceTime();
//        newMachinePriceTime.setPartnerId(machine.getPartnerId());
        newMachinePriceTime.setStatus(0);
        newMachinePriceTime.setIsplatForm((byte)0);
        newMachinePriceTime.setMachineId(machine.getId());
        newMachinePriceTime.setCreate_time(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        newMachinePriceTime.setTimeName(machine.getName());
        newMachinePriceTime.setType(priceTime.getType());
        this.priceTimeService.insert(newMachinePriceTime);
        return changeRow;
    }

//    public static void main(String[] args) {
//
//        System.out.println(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
//    }
    public List<Object> queryStoreMachine(Integer[]  storeIds,Integer partnerId)
    {
        if(storeIds.length==0)
        {
            return Arrays.asList(this.machineDao.getMachinesByPartnerId(partnerId).toArray());
        }
        List<Object> stringList=new ArrayList<>();
        for (Integer sId:storeIds
             ) {
            stringList.add(this.machineDao.queryStoreMachine(sId));
        }

        return stringList == null ? Collections.emptyList() : stringList;
    }

    public int RestartGenCode()
    {
        List<Machine> machineList=this.machineDao.queryAllMachine();
//        List<Coupon> couponList=this.couponService.queryAllCoupons();

        if(machineList.isEmpty())
        {
            return 0;
        }
//        for (Coupon coupon:couponList)
//        {
//            this.couponService.generateWxCode(coupon);
//        }
        if(machineList.isEmpty())
        {
            return 0;
        }
        for (Machine machine:machineList
             ) {
            this.generateWxCode(machine);
            this.priceTimeService.restartPriceTime(machine.getId());
        }
        return 1;

    }
    public List<Store> queryStore(Integer  partnerIds)
    {
        return  this.storeService.getPartnerList(partnerIds);
    }
    public Machine getMachineByMachineId(int machineId)
    {
        Machine machine=this.machineDao.queryMachineById(machineId);
        return machine;
    }
    public String generateWxCode(Machine machine) {
        String fileName = "machine_wxCode_" + StringUtil.getRandomUUID("10") +"_"+machine.getId()+ ".jpeg";
        String wxCodeUrl = this.wxService.getWxACodeFromWx("m=" + machine.getId()+"&t=2", fileName, "pages/index/index");
        if (StringUtils.isNotBlank(wxCodeUrl)) {
            machine.setWxCodeUrl(wxCodeUrl);
            int changeRow = this.machineDao.updateMachine(machine);
            if (changeRow == 0) {
                logger.info(String.format("update machine wxCode fail, machineId = %s, wxCodeUrl = %s", machine.getId(), wxCodeUrl));
                return null;
            } else {
                return wxCodeUrl;
            }
        } else {
            return null;
        }
    }

    public Machine queryMachineById(int id) {
        return this.machineDao.queryMachineById(id);
    }

    public List<Machine> getMachines(Map<String, Object> filterCondition) {
        List<Machine> machine = this.machineDao.queryMachines(filterCondition);
        return machine == null ? Collections.emptyList() : machine;
    }

    List<Machine> queryMachineByIds(List<String> idList) {
        List<Machine> machine = this.machineDao.queryMachineByIds(idList);
        return machine == null ? Collections.emptyList() : machine;
    }

    public int deleteMachine(int id) {
        return this.machineDao.updateMachineStatus(id, 0);
    }

    public int updateMachine(Machine machine) {

        return this.machineDao.updateMachine(machine);
    }

    public List<Machine> getAllMachine() {
        List<Machine> machines = this.machineDao.queryAllMachine();
        return machines == null ? Collections.emptyList() : machines;
    }

    public Machine getMachineByName(String name) {
        return this.machineDao.queryMachineByName(name);
    }

    int setMachinePartnerId(int partnerId, List<String> nameList) {
        return CollectionUtils.isEmpty(nameList) ? 0 : this.machineDao.setMachinePartnerId(partnerId, nameList);
    }

    public List<Machine> getMachinesByPartnerId(int partnerId) {
        return this.machineDao.getMachinesByPartnerId(partnerId);
    }

    public int removeMachineOfPartner(int partnerId) {
        return this.machineDao.removeMachineOfPartner(partnerId);
    }

    int changeMachineWorkStateOccupied(int machineId) {
        return this.machineDao.updateMachineWorkState(101, machineId);
    }

    int changeMachineWorkStateUnOccupied(int machineId) {
        return this.machineDao.updateMachineWorkState(102, machineId);
    }

    public  void startMachine(String orderSn,String machineId)
    {
        this.openMachine(machineId, orderSn);
    }


    String receiveMessageFromApp(String machineId, String message) {
        try {
            JSONObject jsonObject = new JSONObject(message);
            String operate = jsonObject.getString("operate");
            String wsstatus = jsonObject.getString("wsstatus");
            String ordersn="";
            logger.info("记录--收到指令："+jsonObject);
            if (MachineOperate.START.getOperate().equalsIgnoreCase(operate)) {
                String orderSn = jsonObject.getString("orderSn");
                logger.info("记录--start："+jsonObject);
                if(StringUtil.isEmpty(orderSn))
                {
                    return (new JSONObject(ReturnUtil.Error("订单号获取异常"))).toString();
                }
                if(!this.orderService.queryOrderByOrderSn(orderSn).getMachineId().equals(Integer.parseInt(machineId)))
                {
                    return (new JSONObject(ReturnUtil.Error("订单号与机器不一致"))).toString();
                }
                    //注释：消除小程序启动设备的指令
                if(this.orderService.queryOrderInfoByOrderSn(orderSn).getPayPrice().intValue()==0)
                {
//                    logger.info("会员卡+++++"+jsonObject);
                    return   (new JSONObject(this.openMachine(machineId, orderSn))).toString();
                }
              return   (new JSONObject(this.connectMachine(machineId,orderSn)).toString());
            } else
                if(MachineOperate.RESET.getOperate().equalsIgnoreCase(operate)){
                String orderSn = jsonObject.getString("orderSn");
                boolean rs = this.sendReset2Machine(machineId,orderSn);
                ModelMap res=!rs ? ReturnUtil.socketError(ResultState.FAIL_SEND_MESSAGE.getMsg())
                       : ReturnUtil.socketSuccess(ResultState.SUCCESS_SEND_MESSAGE.getMsg());
//                JSONObject object=new JSONObject();
//                object.put("res",res);
//                object.put("wsststus","2");
                return (new JSONObject(res)).toString();
            } else if(MachineOperate.CHECK.getOperate().equalsIgnoreCase(operate))
            {
//                String wsstatus = jsonObject.getString("wsstatus");
                String orderSn = jsonObject.getString("orderSn");
                String machineId1 = jsonObject.getString("machineId");
                String washType = jsonObject.getString("washType");
                String status = jsonObject.getString("status");
                JSONObject json=new JSONObject();
                json.put("wsstatus","2");
                json.put("orderSn",orderSn);
                json.put("machineId",machineId1);
                json.put("washType",washType);
                json.put("status",status);
                return (new JSONObject(json).toString());
            }
            else {
                if(!StringUtil.isNullOrEmpty(jsonObject.getString("orderSn")))
                {
                    ordersn=jsonObject.getString("orderSn");
                }
                return MachineOperate.STOP.getOperate().equalsIgnoreCase(operate) ? (new JSONObject(this.stopMachine(machineId,ordersn))).toString() : (new JSONObject(ReturnUtil.socketError(ResultState.UNRECOGNIZED_COMMAND.getMsg()))).toString();
            }
        } catch (Exception var6) {
            logger.error("catch error when receive message from app", var6);
            return (new JSONObject(ReturnUtil.Error(var6.getMessage()))).toString();
        }
    }
    String receiveStartMessageFromApp(String orderSn,String machineId, String message) {
        try {
            logger.info("记录--收到指令："+message);
            if (MachineOperate.START.getOperate().equalsIgnoreCase(message)) {
//                String orderSn = jsonObject.getString("orderSn");
                logger.info("记录--start："+message);
                if(StringUtil.isEmpty(orderSn))
                {
                    return (new JSONObject(ReturnUtil.Error("订单号获取异常"))).toString();
                }
                return   (new JSONObject(this.openMachine(machineId, orderSn))).toString();
            }
        } catch (Exception var6) {
            logger.error("catch error when receive message from app", var6);
            return (new JSONObject(ReturnUtil.Error(var6.getMessage()))).toString();
        }
        return "";
    }
    //小程序归位设备消息chuan
    private boolean sendReset2Machine(String machineId, String orderSn) {
        JSONObject message = new JSONObject();
        message.put("machineId", Integer.valueOf(machineId));
        message.put("orderSn", orderSn);
        message.put("operate", MachineOperate.RESET.getOperate());
        message.put("messageId", CommonUtil.generateMessageId());
        message.put("ack",true);
        return this.mqttService.sendMsg(machineId, message.toString());
    }

    //新加
    public boolean resetMachineH5ByPartner(Integer machineId, Integer partnerId)
    {
        return sendReset2Machine(machineId.toString(),"resetMachineByPartner"+partnerId);
    }


    public List<Object> getNearByMachine(String Lng,String Lat,HttpServletRequest result) throws UnsupportedEncodingException {

        List<SysDic> dicNearBy =sysDicService.getByCode(1008);
        Double around=dicNearBy.isEmpty()==true?10.0:Double.valueOf(dicNearBy.get(0).getValue());
        List<Machine> machines = this.machineDao.queryAllWorkingMachine();
       logger.info(machines.toString());
        if(machines.isEmpty())
        {
            return Collections.emptyList();
        }
        Map<String,Object> node = null;
        List<Object> list=new ArrayList<>();
        for (Machine machine:machines ) {
            node = new HashMap<>();
            String destinations=machine.getLatitude().toString()+","+machine.getLongitude().toString();
            String origins=Lat+","+Lng;
            String s=MapUtils.showMap(origins,destinations,result);
            if(!s.equals(""))
            {
            Double distance=Double.valueOf(s)/1000;
            if(distance<=around)
            {
                node.put("id", machine.getId());
                node.put("name", machine.getName());
                node.put("addr", machine.getAddress());
                node.put("lng", machine.getLongitude());
                node.put("lat", machine.getLatitude());
//              node.put("distanceByKM", CaculateDistance.getDistanceMeter(Lng,Lat,machine.getLongitude().toString(),machine.getLatitude().toString()));
                node.put("distance",String.format("%.2f",distance));
                node.put("status", machine.getStatus());
                node.put("online", machine.getOnline());
                node.put("workstate", machine.getWorkState());
                node.put("dayDes", machine.getDayDes());
                node.put("nightDes", machine.getNightDes());
                node.put("stopDes", machine.getStopDes());
                node.put("recoveryTime", machine.getRecoveryTime());
                node.put("isDirect", machine.getIsDirect());
                Coupon coupon=couponService.getCouponByMachine(machine.getId());
                if (coupon!=null)
                {
                    node.put("couponStatus",1);
                    node.put("couponId", coupon.getCouponId());
                    node.put("couponName",coupon.getCouponName());
                    node.put("couponType",coupon.getType());
                    if(coupon.getType()==1)
                    {
                        node.put("Price",coupon.getCouponPrice());
                        node.put("fullPrice",coupon.getFullPrice());
                    }else{
                        node.put("Price",coupon.getCouponRate());
                    }
                }else {
                    node.put("couponStatus",0);
                    /**
                     * couponStatus:0无优惠券，1存在优惠券
                     * couponId：优惠券Id
                     *couponName:优惠券名称
                     * couponType：1为满减优惠券。2为折扣优惠券
                     * price：当type为1时，为减去的价格，type为2时，为折扣
                     * fullprice：满多少价格使用
                     */
                }
                list.add(node);
            }}
        }
        return list;
    }

    //用户建立长连接之后，紧接着给设备发送消息，提示设备刷新进程

    public  ModelMap connectMachine(String machineId,String orderSn)
    {
        Machine machine=new Machine();
        OrderInfo orderInfo = this.orderService.queryOrderInfoByOrderSn(orderSn);
        machine.setId(Integer.parseInt(machineId));
        this.sendConnectMachineMessage(machine,orderInfo);
        return ReturnUtil.socketSuccess("设备刷新进程成功");
    }

        //更改设备是否运行状态
    public int setMachineOperate(int is_operate,String machineId)
    {
        int change=this.machineDao.updateMachineOperate(is_operate,machineId);
        return change;
    }

    /**
     * 该方法用于发送指令给小程序后告知设备需要更新进程
     */
    public void replyMachineByStart(String machineId,String orderSn)
    {
        Machine machine=new Machine();
        OrderInfo orderInfo = this.orderService.queryOrderInfoByOrderSn(orderSn);
        machine.setId(Integer.parseInt(machineId));
        this.sendConnectMachineMessage(machine,orderInfo);
    }

    private ModelMap openMachine(String machineId, String orderSn) {
        Machine machine = this.queryMachineById(Integer.parseInt(machineId));

        if (machine == null) {
            return ReturnUtil.socketError(ResultState.EXIST_NO_MACHINE.getMsg());
        } else {
            if(!this.orderService.queryOrderByOrderSn(orderSn).getMachineId().equals(machine.getId()))
            {
                return ReturnUtil.socketError(ResultState.EXIST_NO_MACHINE.getMsg());
            }
            OrderInfo orderInfo = this.orderService.queryOrderInfoByOrderSn(orderSn);
            if (orderInfo == null) {
                return ReturnUtil.socketError(ResultState.ORDER_NOT_EXIST.getMsg());
            } else if (orderInfo.getPayStatus() != null && orderInfo.getPayStatus() == 2) {
                if (orderInfo.orderConsumed())
                {
                    logger.info("记录--订单情况："+orderInfo.toString());
                    return ReturnUtil.socketError(ResultState.ORDER_IS_CONSUMED.getMsg());
                }
                    boolean isSuccess = this.sendOpenMachineMessage(machine, orderInfo);
                    //启动命令发送成功将订单改为已消费(暂时取消)
                    if(isSuccess) {
                        //将订单服务状态改为正在进行中
                        orderInfo.setServiceStatus(0);
                        this.orderService.updateOrder(orderInfo);
                    }
                    return (!isSuccess ? ReturnUtil.socketError(ResultState.FAIL_SEND_MESSAGE.getMsg()) : ReturnUtil.socketSuccess(ResultState.SUCCESS_SEND_MESSAGE.getMsg()));
                }}
                return ReturnUtil.socketError(ResultState.ORDER_IS_NOT_PAYED.getMsg());
    }

    //新加
    public boolean startMachineH5ByPartner(Machine machine, OrderInfo orderInfo)
    {
        orderInfo.setOrderSn("startMachineByPartner"+machine.getPartnerId());
        return sendOpenMachineMessage(machine,orderInfo);
    }



    private boolean sendOpenMachineMessage(Machine machine, OrderInfo orderInfo) {
        JSONObject message = new JSONObject();
        message.put("machineId", machine.getId());
        message.put("orderSn", orderInfo.getOrderSn());
        message.put("washType", orderInfo.getServiceId());
        message.put("operate", MachineOperate.START.getOperate());
        message.put("messageId", CommonUtil.generateMessageId());
        //新加ACK确认字段
        message.put("ack",true);
        Boolean flag=this.mqttService.sendMsg(String.valueOf(machine.getId()), message.toString());
        //开始机器，保存洗车图片
        try{
            this.lappService.saveOrderCarWashImage(orderInfo,machine);
        }catch (Exception e)
        {
            logger.info("保存洗车图片失败");
            e.printStackTrace();
        }
        return flag;
    }
        //解决用户成功付款之后，点击完成，刷新不了进程问题处理办法
        private boolean sendConnectMachineMessage(Machine machine, OrderInfo orderInfo) {
            JSONObject message = new JSONObject();
            message.put("machineId", machine.getId());
            message.put("orderSn", orderInfo.getOrderSn());
            message.put("washType", orderInfo.getServiceId());
            message.put("operate", MachineOperate.CONNECT.getOperate());
            message.put("messageId", CommonUtil.generateMessageId());
            message.put("ack",true);
            return this.mqttService.sendMsg(String.valueOf(machine.getId()), message.toString());
        }


    /**
     * 查询洗车模式价格
      * @param machineId
     * @return
     */
    public Map<String, Object> getMachineStatus(Integer machineId)
    {
        Map<String, Object> machineStatus = new HashMap<>();
        machineStatus.put("quickWash",false);  //快洗
        machineStatus.put("generalWash",false);  //普洗
        machineStatus.put("fineWash",false); //精洗
        //机器对象
        Machine machine=this.getMachineByMachineId(machineId);
        List<String> machinePriceList=new ArrayList<>();
        if(!StringUtil.isNullOrEmpty(machine))
        {
            if(!StringUtil.isNullOrEmpty(machine.getPriceIds()))
            {
                String s=machine.getPriceIds();
                String [] s1=s.split(",");
                machinePriceList= Arrays.asList(s1);
                System.out.println(machinePriceList);
                for (String price:machinePriceList
                ) {
                    switch (Integer.parseInt(price))
                    {
                        case 1:machineStatus.put("quickWash",true);break;
                        case 2:machineStatus.put("generalWash",true);break;
                        case 3:machineStatus.put("fineWash",true);
                    }
                }
            }else{
                machineStatus.put("quickWash",true);  //快洗
                machineStatus.put("generalWash",true);  //普洗
                machineStatus.put("fineWash",true); //精洗
            }
        }
        return machineStatus;
    }




    private ModelMap stopMachine(String machineId,String ordersn) {
        boolean isSuccess = this.sendStopMachineMessage(machineId,ordersn);
        return !isSuccess ? ReturnUtil.socketError(ResultState.FAIL_SEND_MESSAGE.getMsg()) : ReturnUtil.socketSuccess(ResultState.SUCCESS_SEND_MESSAGE.getMsg());
    }

    //新加
    public boolean stopMachineH5ByPartner(Integer machineId, Integer partnerId)
    {
       return sendStopMachineMessage(machineId.toString(),"stopMachineByPartner"+partnerId);
    }


    private boolean sendStopMachineMessage(String machineId,String ordersn) {
        JSONObject message = new JSONObject();
        message.put("machineId", machineId);
        message.put("operate", MachineOperate.STOP.getOperate());
        message.put("messageId", CommonUtil.generateMessageId());
        message.put("ack",true);
        message.put("orderSn",ordersn);
        return this.mqttService.sendMsg(machineId, message.toString());
    }

    void changeMachineOnlineState(String machineId, int online) {
        int changeRows = this.machineDao.changeMachineOnlineState(machineId, online);
        if (changeRows > 0) {
            logger.info(String.format("success to update machine online, machienId = %s, online = %s", machineId, online));
        } else {
            logger.info(String.format("fail to update machine online, machienId = %s, online = %s", machineId, online));
        }

    }

    public List<Machine> queryUnRelatedMachines() {
        List<Machine> unRelatedMachines = this.machineDao.queryUnRelatedMachines();
        if (unRelatedMachines == null) {
            unRelatedMachines = Collections.emptyList();
        }

        return unRelatedMachines;
    }

    public boolean resetMachine(int machineId) {
        Machine machine = new Machine();
        machine.setId(machineId);
        machine.setStatus(1);
        machine.setWorkState(102);
        machine.setOnline(0);
        return this.machineDao.updateMachine(machine) > 0;
    }
    //============new  lyj===================
    public Object getAllMachine(String lng, String lat) {
        List<Machine> list =this.getAllMachine();
        List<Map<String,Object>> nodes =new ArrayList<>();

        Map<String,Object> node = null;
        for (Machine machine:list ) {
            node = new HashMap<>();
            node.put("id",machine.getId());
            node.put("name",machine.getName());
            node.put("addr",machine.getAddress());
            node.put("lng",machine.getLongitude());
            node.put("lat",machine.getLatitude());
            node.put("distanceByKM", CaculateDistance.getDistanceMeter(lng,lat,machine.getLongitude().toString(),machine.getLatitude().toString()));
            node.put("status",machine.getStatus());
            node.put("online",machine.getOnline());
            node.put("workstate",machine.getWorkState());
            node.put("dayDes",machine.getDayDes());
            node.put("nightDes",machine.getNightDes());
            node.put("stopDes",machine.getStopDes());
            node.put("recoveryTime",machine.getRecoveryTime());
            node.put("isDirect",machine.getIsDirect());
            nodes.add(node);
        }
        return nodes;
    }

    public String queue_up(Integer machineId) {
        //Machine  m = this.machineDao.queryMachineById(machineId);
        String img = (String) redisService.get("queue_up_img" + machineId);
        if(null ==img){
            try {
                int geting = 0;
                sendGetMachineImg(machineId+"");
                while (geting <8000) {
                    img = (String) redisService.get("queue_up_img" + machineId);
                    if (null == img) {
                        geting += 1000;
                        Thread.sleep(1000);
                    }else{
                        geting = 9000;
                    }
                }
            } catch (Exception e) {
                logger.error("["+machineId+"]获取排队视频失败");
            }
        }
        return img;
    }

    private boolean sendGetMachineImg(String machineId) {
        JSONObject message = new JSONObject();
        message.put("machineId", machineId);
        message.put("operate", MachineOperate.GETIMG.getOperate());
        message.put("messageId", CommonUtil.generateMessageId());
        message.put("ack",true);
        return this.mqttService.sendMsg(String.valueOf(machineId), message.toString());
    }


    private boolean carStopIsOk(String machineId) {
        //{"machineId":51,"operate":"status","orderSn":"order_nKg6c8bKamCHGfGBIvkAmvAmxi","messageId":"1a2212df-e29b-4c23-a392-5bb5653524e2","washType":1}
        JSONObject message = new JSONObject();
        message.put("machineId", machineId);
        message.put("operate", "status");
        message.put("orderSn", "");
        message.put("messageId", CommonUtil.generateMessageId());
        message.put("washType", 1);
        message.put("ack",true);
        return this.mqttService.sendMsg(String.valueOf(machineId), message.toString());
    }


    public String carStopIsOk(Integer machineId) {
        //Machine  m = this.machineDao.queryMachineById(machineId);
        String img =null;// (String) redisService.get("carStopIsOk_" + machineId);
        if(null ==img){
            try {
                int geting = 0;
                carStopIsOk(machineId+"");
                while (geting <8000) {
                    //img = (String) redisService.get("carStopIsOk_" + machineId);
                    if (MqttService.carIsStop.containsKey("carStopIsOk_" + machineId)) {
                        img =MqttService.carIsStop.get("carStopIsOk_" + machineId);
                        geting = 9000;
                    }else{
                        geting += 1000;
                        Thread.sleep(1000);
                    }
                }
            } catch (Exception e) {
                logger.error("["+machineId+"]获取车辆是否停到位了失败");
            }
        }
        return img;
    }

    public ModelMap updateMachineStatus(Machine machine) {
        String msg =null;
        if (machine == null) {
            return ReturnUtil.Error(ResultState.MACHINE_IS_NULL.getMsg());
        } else {
            if(machine.getOnline()==null && machine.getStatus()==null){
                return ReturnUtil.Error("无效状态");
            }
            if(machine.getOnline()!=null){
                if(machine.getOnline()==0){
                    msg="{\"leave\":\"333333\",\"machineId\":\""+machine.getId()+"\", \"orderSn\": \"orderSn 123 \", \"message\": {\"level\": \"D\", \"messageCode\": \"D-02\", \"status\": 0, \"ack\": \"true\", \"messageId\": \""+CommonUtil.generateMessageId()+"\"}}";
                }else if(machine.getOnline()==1){
                    msg="{\"machineId\": \""+machine.getId()+"\", \"orderSn\": \"orderSn 123 \", \"message\": {\"level\": \"D\", \"messageCode\": \"D-01\", \"status\": 1,\"ack\": \"true\", \"messageId\": \""+CommonUtil.generateMessageId()+"\"}}";
                    machine.setStatus(1);
                }else{
                    return ReturnUtil.Error("无效状态");
                }
            }
            if(machine.getStatus()!=null){
                if(machine.getStatus()==2){
                    msg="{\"leave\":\"D\",\"machineId\":\""+machine.getId()+"\", \"orderSn\": \"orderSn 123 \", \"message\": {\"level\": \"D\", \"messageCode\": \"D-03\", \"status\": 3, \"ack\": \"true\", \"messageId\": \""+CommonUtil.generateMessageId()+"\"}}";
                }else if(machine.getStatus()==1){
                    msg="{\"machineId\": \""+machine.getId()+"\", \"orderSn\": \"orderSn 123 \", \"message\": {\"level\": \"D\", \"messageCode\": \"D-01\", \"status\": 1,\"ack\": \"true\", \"messageId\": \""+CommonUtil.generateMessageId()+"\"}}";
                }else{
                    return ReturnUtil.Error("无效状态");
                }
            }
            if(StringUtils.isNotBlank("msg")){
                this.mqttService.sendMsg(String.valueOf(machine.getId()),msg);
            }
        }
        int result = this.updateMachine(machine);
        if (result == 0) {
            logger.info("update machine fail", machine);
            return ReturnUtil.Error(ResultState.UPDATE_MACHINE_FAIL.getMsg());
        } else {
            return ReturnUtil.Success(ResultState.UPDATE_MACHINE_SUCCESS.getMsg());
        }
    }
    int setMachinePartnerIdById(int partnerId, List<Machine> machines) {
        return CollectionUtils.isEmpty(machines) ? 0 : this.machineDao.setMachinePartnerIdById(partnerId, machines);
    }
    //
    public List<Machine> getCouponMachines(Integer id) {

        return machineDao.getCouponMachines(id);
    }
    //===============
}


/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.MachineOperate;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.MachineDao;
import com.wsd.smartcarwasher.domain.Machine;
import com.wsd.smartcarwasher.domain.OrderInfo;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class MachineService {
    private static final Logger logger = LoggerFactory.getLogger(MachineService.class);

    @Resource
    private MachineDao machineDao;

    @Resource
    @Lazy
    private WxService wxService;

    @Lazy
    @Resource
    private MqttService mqttService;

    @Resource
    private OrderService orderService;

    @Transactional
    public int addMachine(Machine machine) {
        String fileName = Global.FILE_NAME_PREFIX_MACHINE_WX_CODE + machine.getName() + Global.FILE_NAME_FORMAT_JPEG;
        machine.setStatus(Global.MACHINE_STATUS_CLOSE);
        machine.setWorkState(Global.MACHINE_WORK_STATE_UNOCCUPIED);
        if (StringUtils.isBlank(machine.getServiceTime())) {
            machine.setServiceTime(Global.DEFAULT_SERVICE_TIME);
        }
        int changeRow = machineDao.addMachine(machine);
        if (changeRow > 0) {
            String wxCodeUrl = wxService.getWxACodeFromWx("machineId=" + machine.getId(), fileName, "pages/prepare-steps/prepare-steps");
            if (StringUtils.isNotBlank(wxCodeUrl)) {
                machine.setWxCodeUrl(wxCodeUrl);
                machineDao.updateMachine(machine);
            }
        }
        return changeRow;
    }

    public Machine queryMachineById(int id) {
        return machineDao.queryMachineById(id);
    }

    public List<Machine> getMachines(Map<String, Object> filterCondition) {
        List<Machine> machine = machineDao.queryMachines(filterCondition);
        if (machine == null) {
            return Collections.emptyList();
        }
        return machine;
    }

    List<Machine> queryMachineByIds(List<String> idList) {
        List<Machine> machine = machineDao.queryMachineByIds(idList);
        if (machine == null) {
            return Collections.emptyList();
        }
        return machine;
    }

    public int deleteMachine(int id) {
        return machineDao.updateMachineStatus(id, Global.MACHINE_STATUS_REMOVE);
    }

    public int updateMachine(Machine machine) {
        return machineDao.updateMachine(machine);
    }

    public List<Machine> getAllMachine() {
        List<Machine> machines = machineDao.queryAllMachine();
        if (machines == null) {
            return Collections.emptyList();
        }
        return machines;
    }

    public Machine getMachineByName(String name) {
        return machineDao.queryMachineByName(name);
    }

    void setMachinePartnerId(int partnerId, List<String> nameList) {
        if (CollectionUtils.isEmpty(nameList)) {
            return;
        }
        int changeRows = machineDao.setMachinePartnerId(partnerId, nameList);
    }

    public List<Machine> getMachinesByPartnerId(int partnerId) {
        return machineDao.getMachinesByPartnerId(partnerId);
    }

    public int removeMachineOfPartner(int partnerId) {
        return machineDao.removeMachineOfPartner(partnerId);
    }

    //修改机器状态为被占用
    int changeMachineWorkStateOccupied(int machineId) {
        return machineDao.updateMachineWorkState(Global.MACHINE_WORK_STATE_OCCUPIED, machineId);
    }

    //修改机器状态为空闲
    int changeMachineWorkStateUnOccupied(int machineId) {
        return machineDao.updateMachineWorkState(Global.MACHINE_WORK_STATE_UNOCCUPIED, machineId);
    }

    String receiveMessageFromApp(String machineId, String message) {
        try {
            JSONObject jsonObject = new JSONObject(message);
            String operate = jsonObject.getString("operate");
            if (MachineOperate.START.getOperate().equalsIgnoreCase(operate)) {
                String orderSn = jsonObject.getString("orderSn");
                return new JSONObject(openMachine(machineId, orderSn)).toString();
            } else if (MachineOperate.STOP.getOperate().equalsIgnoreCase(operate)) {
                return new JSONObject(stopMachine(machineId)).toString();
            } else {
                return new JSONObject(ReturnUtil.Error(ResultState.UNRECOGNIZED_COMMAND.getMsg())).toString();
            }
        } catch (Exception e) {
            logger.error("catch error when receive message from app", e);
            return new JSONObject(ReturnUtil.Error(e.getMessage())).toString();
        }
    }

    private ModelMap openMachine(String machineId, String orderSn) {
        Machine machine = queryMachineById(Integer.parseInt(machineId));
        if (machine == null) {
            return ReturnUtil.Error(ResultState.EXIST_NO_MACHINE.getMsg());
        }
        //if (Global.MACHINE_WORK_STATE_OCCUPIED == machine.getWorkState()) {
        //    return ReturnUtil.Error(ResultState.MACHINE_STATUS_EXCEPTION.getMsg());
        //}
        OrderInfo orderInfo = orderService.queryOrderInfoByOrderSn(orderSn);
        if (orderInfo == null) {
            return ReturnUtil.Error(ResultState.ORDER_NOT_EXIST.getMsg());
        }
        if (orderInfo.getPayStatus() == null || orderInfo.getPayStatus() != Global.ORDER_PAY_STATUS_PAID) {
            return ReturnUtil.Error(ResultState.ORDER_IS_NOT_PAYED.getMsg());
        }
        if (orderInfo.orderConsumed()) {
            return ReturnUtil.Error(ResultState.ORDER_IS_CONSUMED.getMsg());
        }
        boolean isSuccess = sendOpenMachineMessage(machine, orderInfo);
        if (!isSuccess) {
            return ReturnUtil.Error(ResultState.FAIL_SEND_MESSAGE.getMsg());
        }
        return ReturnUtil.Success(ResultState.SUCCESS_SEND_MESSAGE.getMsg());
    }

    private boolean sendOpenMachineMessage(Machine machine, OrderInfo orderInfo) {
        JSONObject message = new JSONObject();
        message.put("machineId", machine.getId());
        message.put("orderSn", orderInfo.getOrderSn());
        message.put("washType", orderInfo.getServiceId());
        message.put("operate", MachineOperate.START.getOperate());
        return mqttService.sendMsg(String.valueOf(machine.getId()), message.toString());
    }

    private ModelMap stopMachine(String machineId) {
//        Machine machine = queryMachineById(Integer.parseInt(machineId));
//        if (machine == null) {
//            return ReturnUtil.Error(ResultState.EXIST_NO_MACHINE.getMsg());
//        }
//        if (Global.MACHINE_WORK_STATE_OCCUPIED != machine.getWorkState()) {
//            return ReturnUtil.Error(ResultState.MACHINE_STATUS_EXCEPTION.getMsg());
//        }
        boolean isSuccess = sendStopMachineMessage(machineId);
        if (!isSuccess) {
            return ReturnUtil.Error(ResultState.FAIL_SEND_MESSAGE.getMsg());
        }
        return ReturnUtil.Success(ResultState.SUCCESS_SEND_MESSAGE.getMsg());
    }

    private boolean sendStopMachineMessage(String machineId) {
        JSONObject message = new JSONObject();
        message.put("machineId", machineId);
        message.put("operate", MachineOperate.STOP.getOperate());
        return mqttService.sendMsg(machineId, message.toString());
    }
}
*/
